package org.chen.config;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

@Configuration
public class RabbitMQConsumerConfig {
    
    @Bean
    public SimpleRabbitListenerContainerFactory videoTaskListenerFactory(
            ConnectionFactory connectionFactory,
            MessageConverter messageConverter) {
            
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);

        // 配置重试策略
        RetryTemplate retryTemplate = new RetryTemplate();
        // 设置固定间隔重试策略
        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
        backOffPolicy.setBackOffPeriod(5000); // 5秒重试间隔
        retryTemplate.setBackOffPolicy(backOffPolicy);

        // 设置最大重试次数
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(3); // 最多重试3次
        retryTemplate.setRetryPolicy(retryPolicy);

        factory.setRetryTemplate(retryTemplate);

        factory.setMessageConverter(messageConverter);
        
        // 配置并发消费者
        factory.setConcurrentConsumers(3);
        factory.setMaxConcurrentConsumers(5);
        
        // 配置手动确认
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        
        // 配置预取数量
        factory.setPrefetchCount(1);
        
        return factory;
    }
}